import store from '../store'
import { parseData } from './parseData'
import { showToast } from 'vant'

let miotLinkBaseNativeJs_client = null,
  miotLinkBaseNativeJs_puId = null,
  miotLinkBaseNativeJs_modelId = null,
  miotLinkBaseNativeJs_kindId = null,
  miotLinkBaseNativeJs_state = null,
  miotLinkBaseNativeJs_mac = null,
  miotLinkBaseNativeJs_puNickName = null,
  miotLinkBaseNativeJs_cuId = null,
  miotLinkBaseNativeJs_cuName = null,
  miotLinkBaseNativeJs_cuLocation = null,
  miotLinkBaseNativeJs_userdata = null,
  miotLinkBaseNativeJs_language = null,
  miotLinkBaseNativeJs_sequence = null,
  miotLinkBaseNativeJs_init = 'uninit'
const miotLinkBaseNativeJs_payRes = 'payRes'
const define_miotlink_init = JSON.stringify({
  code: 'init',
  data: {
    getInitPuData: true.toString(),
    hiddenPluginTitle: true.toString(),
    getLanguage: true.toString(),
    getCuInfo: true.toString(),
    getStatusBarInfo: false.toString()
  }
})
const define_miotlink_returnDeviceList = JSON.stringify({ code: 'returnDeviceList' })

const define_miotlink_code_initRes = 'initRes', // initRes = 初始化返回
  define_miotlink_code_notifyUartData = 'notifyUartData',
  define_miotlink_code_notifyDeviceState = 'notifyDeviceState',
  define_miotlink_code_getAdditionalInfoRes = 'additionalInfoRes',
  define_miotlink_code_goBackRes = 'goBackRes'

/**********  安卓客戶端 *******************/
window.receiverDeviceData = function (data) {
  // 监听 Android,IOS 端的数据-yu
  console.log('监听客户端的数据', data)
  if (miotLinkBaseNativeJs_init !== 'initOk') {
    console.log('初始化不成功=')
    return
  }
  miotLinkBaseNativeJs_receive(data)
}

/**
 * @description 初始化android, 需要页面一加载的时候就要调用，已在 main.ts文件中调用
 */
export function miotLinkBaseNativeJs_initAndroid() {
  console.log('调用了安卓数据----')
  console.log('miotLinkBaseNativeJs_initAndroid============= ', define_miotlink_init)
  const androidClientData =
    // miotlink_js_bridge.receiveHtmlData => js向框架传递数据
    miotlink_js_bridge.receiveHtmlData(define_miotlink_init)

  console.log('androidClientData==========', androidClientData)
  miotLinkBaseNativeJs_receive(androidClientData)
}
/**
 * @description 向 android 发送数据
 * @param {Object} data
 * @returns
 */
function miotLinkBaseNativeJs_sendToAndroid(data) {
  console.log('miotLinkBaseNativeJs_sendToAndroid=======', data)
  console.log(miotLinkBaseNativeJs_init)
  if (miotLinkBaseNativeJs_init !== 'initOk') {
    console.log('Android-未正确初始化，发送数据不予处理')
    return
  }
  return miotlink_js_bridge.receiveHtmlData(data)
}

/***********  IOS客户端 ******************/
/**
 * IOS端初始化，需要页面一加载的时候就要加载
 */
export function miotLinkBaseNativeJs_initIos() {
  miotLinkBaseNativeJs_sendToIos(define_miotlink_init)
}

/**
 * @description 向 IOS 发送数据
 * @param {Object} data
 */
function miotLinkBaseNativeJs_sendToIos(data) {
  connectWebViewJavascriptBridge(function (bridge) {
    bridge.callHandler('changeNaviStatus', data, function (response) {
      miotLinkBaseNativeJs_receive(response)
    })
    bridge.registerHandler('receiverDeviceData', function (data) {
      miotLinkBaseNativeJs_receive(data)
    })
    if (miotLinkBaseNativeJs_init === 'uninit') {
      bridge.init(function (data, responseCallback) {
        miotLinkBaseNativeJs_receive(data)
      })
      bridge.registerHandler('receiverDeviceData', function (data) {
        miotLinkBaseNativeJs_receive(data)
      })
    }
  })
}

/**
 * 连接WebViewJavascriptBridge
 * 在 native 端和 webview 端注册 Bridge
 */
function connectWebViewJavascriptBridge(callback) {
  if (window.WebViewJavascriptBridge) {
    return callback(WebViewJavascriptBridge)
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(callback)
  }
  window.WVJBCallbacks = [callback]
  const WVJBIframe = document.createElement('iframe')
  WVJBIframe.style.display = 'none'
  WVJBIframe.src = 'https://__bridge_loaded__'
  document.documentElement.appendChild(WVJBIframe)
  setTimeout(function () {
    document.documentElement.removeChild(WVJBIframe)
  }, 0)
  if (window.WebViewJavascriptBridge) {
    callback(WebViewJavascriptBridge)
  } else {
    document.addEventListener(
      'WebViewJavascriptBridgeReady',
      function () {
        callback(WebViewJavascriptBridge)
      },
      false
    )
  }
}

/**
 * @description 接收客户端的反馈
 * @param {string} data
 * @returns
 */
function miotLinkBaseNativeJs_receive(data) {
  console.log('miotLinkBaseNativeJs_receive=============', data)
  if (data == null || data === '') return

  let dataJsonObj = JSON.parse(data)
  console.log('dataJsonObj=====', dataJsonObj)

  let code = dataJsonObj.code.toLowerCase() // 转小写字母

  // 返回手势
  if (code === define_miotlink_code_goBackRes.toLowerCase()) {
    receiveFromNative_goBackRes()
    return
  }
  const clientDataJsonObj = dataJsonObj.data
  if (
    clientDataJsonObj.puId != miotLinkBaseNativeJs_puId &&
    code != define_miotlink_code_getAdditionalInfoRes.toLowerCase() &&
    code != miotLinkBaseNativeJs_payRes.toLowerCase() &&
    code != 'airfruit'
  ) {
    console.log('code==', code)
    //alert("此消息非本设备消息！监听：" + miotLinkBaseNativeJs_puId + ",收到：" + clientDataJsonObj.puId);
    return
  }

  if (code === define_miotlink_code_initRes.toLowerCase()) {
    //收到初始化返回
    console.log('收到初始化返回')
    miotLinkBaseNativeJs_initData(clientDataJsonObj)
  } else if (code === define_miotlink_code_notifyDeviceState.toLowerCase()) {
    //收到设备上下线
    console.log('收到设备上下线')
    receiveFromNative_deviceState(clientDataJsonObj.state, clientDataJsonObj.sequence)
  } else if (code === define_miotlink_code_notifyUartData.toLowerCase()) {
    //收到串口数据
    console.log('收到串口数据')
    receiveFromNative_uartData(clientDataJsonObj.uart.replace(/\s+/g, '')) // 去掉空格
  } else if (code === define_miotlink_code_getAdditionalInfoRes.toLowerCase()) {
    //收到附加信息
    console.log('收到附加信息')
    receiveFromNative_additionalInfoRes(clientDataJsonObj)
  }
}

/**
 * @description 初始化客户端
 * @param {Object} clientInitData
 */
function miotLinkBaseNativeJs_initData(clientInitData) {
  miotLinkBaseNativeJs_client = clientInitData.client
  miotLinkBaseNativeJs_language = clientInitData.language
  miotLinkBaseNativeJs_puId = clientInitData.pu.puId
  miotLinkBaseNativeJs_kindId = clientInitData.pu.kindId
  miotLinkBaseNativeJs_modelId = clientInitData.pu.modelId
  miotLinkBaseNativeJs_userdata = clientInitData.pu.userdata
  miotLinkBaseNativeJs_state = clientInitData.pu.state
  miotLinkBaseNativeJs_mac = clientInitData.pu.mac
  miotLinkBaseNativeJs_puNickName = clientInitData.pu.puNickName
  miotLinkBaseNativeJs_cuId = clientInitData.cu.cuId
  miotLinkBaseNativeJs_cuName = clientInitData.cu.cuName
  miotLinkBaseNativeJs_cuLocation = clientInitData.cu.location

  console.log('miotLinkBaseNativeJs_puNickName=======', miotLinkBaseNativeJs_puNickName)

  miotLinkBaseNativeJs_init = 'initOk'
  // 下发查询全量快照接口
  // sendToNative_sendUartData('F1F1F000F07E')
}

/**
 * @description 返回手势
 */
function receiveFromNative_goBackRes() {
  sendToNative_returnDeviceList()
}
function sendToNative_returnDeviceList() {
  if (miotLinkBaseNativeJs_client === 'Android') {
    miotLinkBaseNativeJs_sendToAndroid(define_miotlink_returnDeviceList)
  } else if (miotLinkBaseNativeJs_client === 'IOS') {
    miotLinkBaseNativeJs_sendToIos(define_miotlink_returnDeviceList)
  } else {
    const u = navigator.userAgent
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 //android终端
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
    if (isAndroid === true) {
      miotLinkBaseNativeJs_sendToAndroid(define_miotlink_returnDeviceList)
    } else if (isiOS === true) {
      miotLinkBaseNativeJs_sendToIos(define_miotlink_returnDeviceList)
    }
  }
}

/**
 * @description 解析上报串口数据
 * @param {String} uartData 串口数据
 *
 */
const receiveFromNative_uartData = uartData => {
  const dataJson = parseData(uartData) // 串口数据的对象
  // showToast(`当前值: 1`)
  console.log('返回的解析数据：', dataJson)
  if (dataJson) {
    store.commit('setDeviceInfo', dataJson)
  }
}

/**
 * @description 发送串口数据
 * @param {string} 串口 例如：F1F1000102037E
 */
export const sendToNative_sendUartData = function (hexUartData) {
  console.log(hexUartData, 'hexUartData')
  hexUartData = hexUartData.replace(/\s+/g, '')

  const data = JSON.stringify({
    code: 'sendDeviceUartData',
    data: {
      puId: miotLinkBaseNativeJs_puId,
      uartDataType: 0,
      uartData: hexUartData
    }
  })

  console.log('我发送的数据=======', data)
  console.log('miotLinkBaseNativeJs_client=========', miotLinkBaseNativeJs_client)
  if (miotLinkBaseNativeJs_client === 'Android') {
    console.log(111)
    miotLinkBaseNativeJs_sendToAndroid(data)
  } else if (miotLinkBaseNativeJs_client === 'IOS') {
    miotLinkBaseNativeJs_sendToIos(data)
  }
}

// 收到附加信息
function receiveFromNative_additionalInfoRes(additionalInfo) {
  let miotPM2_5, city, miotSD, miotTemperature, miotAqi, miotIcon
  if (additionalInfo.hasOwnProperty('values')) {
    miotPM2_5 = additionalInfo.values.miotPM2_5
    city = additionalInfo.values.city
    miotSD = additionalInfo.values.miotSD //湿度
    miotTemperature = additionalInfo.values.miotTemperature //温度
    miotAqi = additionalInfo.values.miotAqi //Aqi
    miotIcon = additionalInfo.values.miotIcon //天气
  } else if (additionalInfo.hasOwnProperty('data')) {
    miotPM2_5 = additionalInfo.data.values.miotPM2_5
    city = additionalInfo.data.values.city
    miotSD = additionalInfo.data.miotSD //湿度
    miotTemperature = additionalInfo.data.miotTemperature //温度
    miotAqi = additionalInfo.data.miotAqi //Aqi
    miotIcon = additionalInfo.data.miotIcon //天气
  }
  var city_location = city.split(',')
}

// 收到设备上下线
function receiveFromNative_deviceState(state, sequence) {
  miotLinkBaseNativeJs_state = state
  miotLinkBaseNativeJs_sequence = sequence
}
